<?php

/**
 * AnswerSystemController
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class AnswerSystemController extends Zend_Controller_Action
{

    public function init()
    {
    	$this->_layout = $this->_helper->layout->getLayoutInstance();
    	$this->_layout->location='answersystem';
    	//$this->checkApp();
    }
    	        
    /**
     * The default action - show the home page
     */
    public function indexAction ()
    {
        // TODO Auto-generated AnswerSystemController::indexAction() default
    	// action
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(Zend_Auth::getInstance()->hasIdentity()&&$myNamespace->userjob=='teacher')
        {
            $this->_redirect('answersystem/teacherdetail');
        }
    	if($this->getRequest()->isPost())
    	{
    	    /*echo '$_POST["class"]='.$this->getRequest()->getParam('class');
    	    echo '$_POST["teachername"]='.$this->getRequest()->getParam('teachername');
    	    echo '$_POST["no1"]='.$this->getRequest()->getParam('no1');
    	    */
    	}
    	
    	$dbapp = new Application_Model_Appiontment();
    	$timenow = time() + 8 * 3600;
    	$where = "`date`>=$timenow and `status`!=1";
    	if(isset($_POST['class'])&&$_POST['class']!=null)
    	{
    	    $class = $_POST['class']; 
    	    $where = $where." and `class` like \"$class\"";
    	}
    	if(isset($_POST['teachername'])&&$_POST['teachername']!=null)
    	{
    	    $teachername = $_POST['teachername'];
    	    $where = $where." and `teacher` like \"$teachername\"";
    	}
    	if(isset($_POST['college'])&&$_POST['college']!=0)
    	{
    	    $college = $_POST['college'];
    	    $where = $where." and `college`=$college";
    	}
    	$array = $dbapp->fetchAll($where,'date')->toArray();
    	
    	/******************分页********************/
        $page =1;//高置默认页
        $numPerPage = 20;//每页显示的条数
        $paginator = Zend_Paginator::factory($array);
        if(isset($_GET['page']) && is_numeric($_GET['page'])){
        	$page = $_GET['page'];//取到URL传过来的页数码
        }
        if($page<=0)$page=1;
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage($numPerPage);
        if($page>=$paginator->count())$page = $paginator->count();
        $this->view->allapp = $paginator;
        $this->view->pagecount = $paginator->count();
        $this->view->page = $page;
		/******************分页********************/
    	$collegeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/college.ini','college');
    	$this->view->collegearray = $collegeconfig->toArray();
    	
    	$myNamespace = new Zend_Session_Namespace('Myspace');
    	if(!isset($myNamespace->userjob))
    	{
    		$this->view->isloggin = false;
    	}
    	else if($myNamespace->userjob=='teacher')
    	{
    		$this->view->isloggin = true;
    		$this->view->author = Zend_Auth::getInstance()->getIdentity();
    		$dbteacher = new Application_Model_Teachers();
    		$teachername = $this->view->author;
    		$where = "`nickname`=\"$teachername\"";
    		$teacher = $dbteacher->fetchRow($where);
    		$this->view->authorimg = $teacher['headimg'];
    	}
    	else
    	{
    		$this->view->isloggin = true;
    		$this->view->author = Zend_Auth::getInstance()->getIdentity();
    		$dbstudent = new Application_Model_Students();
    		$studentname = $this->view->author;
    		$where = "`nickname`=\"$studentname\"";
    		$student = $dbstudent->fetchRow($where)->toArray();
    		$this->view->authorimg = $student['headimg'];
    	}
    }
    public function teacherindexAction()
    {
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(!(Zend_Auth::getInstance()->hasIdentity()&&$myNamespace->userjob=='teacher'))
        {
        	//$this->_redirect('index/login');
        	return;
        	
        }
        else
        {
            $dbapp = new Application_Model_Appiontment();
            $teachername = Zend_Auth::getInstance()->getIdentity();
            $timenow = time() + 8 * 3600;
            $where = "`teacher`=\"$teachername\" and `date`> $timenow and `status`=2";
            $this->view->allapp = $dbapp->fetchAll($where,"date");
        }
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(!isset($myNamespace->userjob))
        {
        	$this->view->isloggin = false;
        }
        else if($myNamespace->userjob=='teacher')
        {
        	$this->view->isloggin = true;
        	$this->view->author = Zend_Auth::getInstance()->getIdentity();
        	$dbteacher = new Application_Model_Teachers();
        	$teachername = $this->view->author;
        	$where = "`nickname`=\"$teachername\"";
        	$teacher = $dbteacher->fetchRow($where);
        	$this->view->authorimg = $teacher['headimg'];
        }
        else
        {
        	$this->view->isloggin = true;
        	$this->view->author = Zend_Auth::getInstance()->getIdentity();
        	$dbstudent = new Application_Model_Students();
        	$studentname = $this->view->author;
        	$where = "`nickname`=\"$studentname\"";
        	$student = $dbstudent->fetchRow($where)->toArray();
        	$this->view->authorimg = $student['headimg'];
        }
    }
    public function teacherdetailAction()
    {
        $pre = 24*3600;
        $pretimeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/pretime.ini','pretime');
        $prearray = $pretimeconfig->toArray();
        $pre = $prearray['pretime'];
        $this->view->pretime = $pre;
        
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(!Zend_Auth::getInstance()->hasIdentity()||$myNamespace->userjob!='teacher')
        {
//         	$this->_redirect('/index/login');
			return;
        	
        }
        $classtime = array(
        		'08:15','09:00','13:55','15:30','19:20'
        );
        //date_default_timezone_set('Asia/Shanghai');
        //$daybegin = '2012/8/5';
        //echo gmdate('Y-m-d H:i:s',time()+8*3600);
        $dbapp = new Application_Model_Appiontment();
        $teachername = Zend_Auth::getInstance()->getIdentity();
        
        $timenow = time() + 8 * 3600;
        //echo '现在时刻：'.gmdate('Y-m-d H:i:s',time()); 
        $daynow = date('w');//从周日开始，从0开始
        if(isset($_GET['id']) && is_numeric($_GET['id']))
        {
            $id = $_GET['id'];
            $app = $dbapp->fetchRow("`id`=$id")->toArray();
            $timenow = $app['date'];
            $daynow = date('w',$timenow);
            //print_r($app);
        }
        //echo '星期'.$daynow;

        $this->view->classtime = $classtime;

        $this->view->week = 0;
        if(isset($_GET['week']) && is_numeric($_GET['week']))//下一周
        {
        	$this->view->week = $this->getRequest()->getParam('week');
        	$this->view->week = $this->view->week>=0?$this->view->week:0;
        }
        $daybeginint = $timenow - $daynow * 24 * 3600 + $this->view->week * 7 * 24 * 3600;
        $daybegin = gmdate('Y/m/d',$daybeginint);
        $this->view->daybegin = $daybegin;
        $timebegin = strtotime($daybegin.'-'.$classtime[0]);
        $timeend = $timebegin + 7*24*3600;//一周内的
        $where = "`teacher`=\"$teachername\" and `date`>=$timebegin and `date`<$timeend";
        $this->view->allapp = $dbapp->fetchAll($where)->toArray();
        $heretime = time()+8*3600;
        $where = "`teacher`=\"$teachername\" and `date`>=$heretime";
        $this->view->alllistapp = $dbapp->fetchAll($where)->toArray();
        
        /*$this->view->collegearray = array('',
         '计算机学院',
        		'软件学院'
        );*/
        $collegeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/college.ini','college');
        $this->view->collegearray = $collegeconfig->toArray();        
        
        if($this->getRequest()->isPost())
        {
            if($this->getRequest()->getParam('class')==null)
                $this->view->tipclass = '课程名不能为空！';
            else if($this->getRequest()->getParam('threshold')==null)
                $this->view->tipthreshold = '人数不能为空！';
            else 
            {
                
                $dbteacher = new Application_Model_Teachers();
                $teacher = $dbteacher->fetchRow("`nickname`=\"$teachername\"")->toArray();
                
                foreach ($_POST as $key=>$value)
                {
                    if($value=='on')
                    {
                        //echo '$_POST['.$key.']='.$value;
                        $classno = intval($key/7);
                        $dayno = $key%7;
                        date_default_timezone_set('Asia/Shanghai');
                        $time = $daybegin.'-'.$classtime[$classno];
                        $data = array(
                        		'teacher'=>$teacher['nickname'],
                        		'college'=>$teacher['college'],
                        		'class'=>$this->getRequest()->getParam('class'),
                        		'date'=>strtotime($time) + $dayno * 24 * 3600,
                        		'countstudent'=>0,
                        		'threshold'=>$this->getRequest()->getParam('threshold'),
                        		'status'=>'2'
                        );
                        $toid = $dbapp->insert($data);
                        if($toid)
                        {
                            $dbteacherappo = new Application_Model_Teacherappo();
                            $dataappo = array(
                                    'teachername'=>$teachername,
                                    'toid'=>$toid
                                    );
                            $dbteacherappo->insert($dataappo);
                        }
                    }
                }
                //print_r($_POST);
                $this->_redirect('/answersystem/teacherdetail?week='.$this->view->week);
            }
        }
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(!isset($myNamespace->userjob))
        {
        	$this->view->isloggin = false;
        }
        else if($myNamespace->userjob=='teacher')
        {
        	$this->view->isloggin = true;
        	$this->view->author = Zend_Auth::getInstance()->getIdentity();
        	$dbteacher = new Application_Model_Teachers();
        	$teachername = $this->view->author;
        	$where = "`nickname`=\"$teachername\"";
        	$teacher = $dbteacher->fetchRow($where);
        	$this->view->authorimg = $teacher['headimg'];
        }
        else
        {
        	$this->view->isloggin = true;
        	$this->view->author = Zend_Auth::getInstance()->getIdentity();
        	$dbstudent = new Application_Model_Students();
        	$studentname = $this->view->author;
        	$where = "`nickname`=\"$studentname\"";
        	$student = $dbstudent->fetchRow($where)->toArray();
        	$this->view->authorimg = $student['headimg'];
        }
        
    }
    public function teachercancelAction()
    {
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(!Zend_Auth::getInstance()->hasIdentity()||$myNamespace->userjob!='teacher')
        {
//         	$this->_redirect('/index/login');
        	return;
        }
        if($this->getRequest()->getParam('id')!=null)
        {
            $id = $this->getRequest()->getParam('id');
            $this->sendcancelmailtostudent($id);//先发送了再删除
            
        	$dbapp = new Application_Model_Appiontment();
        	$dbapp->delete("`id`=$id");
        }
        $week = 0;
        if(isset($_GET['week']) && is_numeric($_GET['week']))
        {
            $week = $_GET['week'];
        }

        $this->_redirect('answersystem/teacherdetail?week='.$week);
        
    }
    public function teachersureAction()
    {
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(!Zend_Auth::getInstance()->hasIdentity()||$myNamespace->userjob!='teacher')
        {
//         	$this->_redirect('/index/login');
			return;	
        }
        if($this->getRequest()->getParam('id')!=null)
        {
            $dbapp = new Application_Model_Appiontment();
            $id = $this->getRequest()->getParam('id');
            $dbapp->changestatus($id, 3);
        }
                $week = 0;
        if(isset($_GET['week']) && is_numeric($_GET['week']))
        {
            $week = $_GET['week'];
        }
        
        $this->sendsuremailtostudent($id);
        
        $this->_redirect('answersystem/teacherdetail?week='.$week);
    }
    public function studentdetailAction()
    {
        $this->indexAction();//加载list
        $dbapp = new Application_Model_Appiontment();
        $dbstudentappo = new Application_Model_Studentappo();
        
        $pre = 24*3600;
        $pretimeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/pretime.ini','pretime');
        $prearray = $pretimeconfig->toArray();
        $pre = $prearray['pretime'];
        $this->view->pretime = $pre;
        
        
        if($this->getRequest()->isPost())
        {
        	if(!Zend_Auth::getInstance()->hasIdentity())
        	{
//         		$this->_redirect('/index/login');
        		return ;
        	}
        	//登记
        	foreach ($_POST as $key=>$value)
        	{
        		if($value=='on')
        		 {
        		//echo '$_POST['.$key.']='.$value;
	        		$appoid = $key;
	        		$dbapp->addastudent($appoid);
	        		$studentname = Zend_Auth::getInstance()->getIdentity();
	        		
	        		$dataappo = array(
	        				'studentname'=>$studentname,
	        				'toid'=>$appoid
	        		);
	        		$dbstudentappo->insert($dataappo);
        		}
        		//print_r($_POST);
        	}
        }
        if(!(isset($_GET['id']) && is_numeric($_GET['id'])))
        {
            $this->_redirect('answersystem/index');
        }
        $classtime = array(
        		'08:15','09:00','13:55','15:30','19:20'
        );
        date_default_timezone_set('Asia/Shanghai');
        $id = $_GET['id'];
        $this->view->requestid = $id;
        //$daybegin = '2012/8/5';
        //echo gmdate('Y-m-d H:i:s',time()+8*3600);
        
        $app = $dbapp->fetchRow("`id`= $id");
        $timethis = $app['date'] - 8*3600;
        //echo gmdate('Y-m-d H:i:s',$timethis);
        $daynow = date('w',$timethis);//从周日开始，从0开始
        //echo '星期'.$daynow;
        
        $daybeginint = $timethis - $daynow * 24 * 3600;
        
        $daybegin = gmdate('Y/m/d',$daybeginint);
        $this->view->classtime = $classtime;
        $this->view->daybegin = $daybegin;
        
        $timebegin = strtotime($daybegin.'-'.$classtime[0]);
        $timeend = $timebegin + 7*24*3600;//一周内的
        $where = "`date`>=$timebegin and `date`<$timeend";
        
        $this->view->alltableapp = $dbapp->fetchAll($where)->toArray();
        //判断该同学是否登记过
        $hasregist = array();
        foreach($this->view->alltableapp as $appitem)
        {
            $keyid = $appitem['id'];
            if(!Zend_Auth::getInstance()->hasIdentity())
            {
                $hasregist[$keyid] = false;
            }
            else
            {
                $studentname = Zend_Auth::getInstance()->getIdentity();
                
                $where = "`studentname`=\"$studentname\" and `toid` = $keyid";
                if($dbstudentappo->fetchAll($where)->count()>0)
                    $hasregist[$keyid] = true;
                else $hasregist[$keyid] = false;
            }
        }
        
        
        
        
        $collegeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/college.ini','college');
        $this->view->collegearray = $collegeconfig->toArray();
        $this->view->hasregist = $hasregist;
        
        
        $myNamespace = new Zend_Session_Namespace('Myspace');
        if(!isset($myNamespace->userjob))
        {
        	$this->view->isloggin = false;
        }
        else if($myNamespace->userjob=='teacher')
        {
        	$this->view->isloggin = true;
        	$this->view->author = Zend_Auth::getInstance()->getIdentity();
        	$dbteacher = new Application_Model_Teachers();
        	$teachername = $this->view->author;
        	$where = "`nickname`=\"$teachername\"";
        	$teacher = $dbteacher->fetchRow($where);
        	$this->view->authorimg = $teacher['headimg'];
        }
        else
        {
        	$this->view->isloggin = true;
        	$this->view->author = Zend_Auth::getInstance()->getIdentity();
        	$dbstudent = new Application_Model_Students();
        	$studentname = $this->view->author;
        	$where = "`nickname`=\"$studentname\"";
        	$student = $dbstudent->fetchRow($where)->toArray();
        	$this->view->authorimg = $student['headimg'];
        }
        //print_r($this->view->hasregist);
        //print_r($this->view->allapp);
    }
    private function checkApp()//$pre为提前时间(s)，检查预约，自动决定
    {
        $pre = 24*3600;
        $pretimeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/pretime.ini','pretime');
        $prearray = $pretimeconfig->toArray();
        $pre = $prearray['pretime'];
        
        $dbapp = new Application_Model_Appiontment();
        $timenow = time() + 8*3600;
        $timejudge = $timenow + $pre;
        $where = "`date` <= $timejudge and `status` = 2";
        $allapp = $dbapp->fetchAll($where);
        foreach($allapp as $app)
        {
            $dbteacher = new Application_Model_Teachers();
            $teachername = $app['teacher'];
            $where = "`nickname`=\"$teachername\"";
            $teacher = $dbteacher->fetchRow($where);
            
            if($app['countstudent']>=$app['threshold'])
            {                
                $this->sendsuremailtostudent($app['id']);
                $this->sendsuremailtoteacher($app, $teacher);
                $dbapp->changestatus($app['id'],3);
            }
            else 
            {
                $this->sendcancelmailtostudent($app['id']);
                $this->sendcancelmailtoteacher($app,$teacher);
                $dbapp->changestatus($app['id'],1);
            }
        }
    }
    private function mailConfigure()
    {
        require_once 'Zend/Mail.php';
        require_once 'Zend/Mail/Transport/Smtp.php';
        
        try {
        
        	$configMail = array(
        			'auth' => 'login',
        			'username' => 'cooljiansir@163.com',
        			'password' => 'dachuangmima2012',
        			'ssl' => 'ssl',
        			'port' => 465
        	);
        	$mailTransport = new Zend_Mail_Transport_Smtp('smtp.163.com',$configMail) ;
        	Zend_Mail::setDefaultTransport($mailTransport);
        	}
        	catch (Zend_Exception $e) {
        		// Here you can log an Zend_Mail exceptions
        		echo $e->getMessage();
        	}
    }
    private function sendsuremailtoteacher($app,$teacher)
    {
        $this->mailConfigure();
        try {
            $mail = new Zend_Mail();
            $mail->addTo($teacher['mail']);
            $title = '决定您在'.gmdate('Y年m月d日H:i',$app['date']).'的答疑';
            $content = '尊敬的'.$teacher['nickname'].'老师:'."\n"
            					.'您好！由于预约了您在'.
            					gmdate('Y年m月d日H:i',$app['date']).'对'.$app['class'].
            					'科目的答疑人数已经达到您你要求，系统自动确定了该次答疑，'.
            					'并邮件通知了所有预约的同学。'."\n\n\n\n\n\n".
            					"祝好！\n".
            					"----------------\n\n".
            					'四川大学网上第二课堂系统';
            $mail->setSubject($title);
            $mail->setBodyText($content);
            $mail->setFrom('cooljiansir@163.com');
            $mail->send();
        }
        catch (Zend_5250_Exception $e){
            echo $e;
        }
    }
    private function sendcancelmailtoteacher($app,$teacher)
    {
        $this->mailConfigure();
        try {
            $mail = new Zend_Mail();
            $mail->addTo($teacher['mail']);
            $title = '取消您在'.gmdate('Y年m月d日H:i',$app['date']).'的答疑';
            $content = '尊敬的'.$teacher['nickname'].'老师:'."\n"
            					.'您好！由于预约了您在'.
            					gmdate('Y年m月d日H:i',$app['date']).'对'.$app['class'].
            					'科目的答疑人数没有达到您你要求，系统自动取消了该次答疑，'.
            					'并邮件通知了所有预约的同学。'."\n\n\n\n\n\n".
            					"祝好！\n".
            					"----------------\n\n".
            					'四川大学网上第二课堂系统';
            $mail->setSubject($title);
            $mail->setBodyText($content);
            $mail->setFrom('cooljiansir@163.com');
            $mail->send();
        }
        catch (Zend_5250_Exception $e){
        	echo $e;
        }
    }
	private function sendsuremailtostudent($id)
	{
	    $this->mailConfigure();
		try {
			// defines gmail smtp infrastructure as default for any email message originated by Zend_Mail.
			
// 			$mail = new Zend_Mail();
// 			$mail->setBodyText('testing gmail');
// 			$mail->setFrom('cooljiansir@163.com');
// 			$mail->addTo('1534509022@qq.com');
// 			$mail->setSubject('静态测试TestSubject—–');
// 			$mail->send();
// 			echo '已发送';
			
			$dbstudentappo = new Application_Model_Studentappo();
			$dbapp = new Application_Model_Appiontment();
			$dbstudent = new Application_Model_Students();
			$allstudent = $dbstudentappo->fetchAll("`toid`=$id");
			$app = $dbapp->fetchRow("`id`=$id");
			 
			$collegeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/college.ini','college');
			$collegearray = $collegeconfig->toArray();
			//print_r($allstudent);
			foreach($allstudent as $student)
			{
				$mail = new Zend_Mail();
				$studentname = $student['studentname'];
				$where = "`nickname` = \"$studentname\"";
				echo 'where'.$where;
				$tostudent = $dbstudent->fetchRow($where)->toArray();
				print_r($tostudent);
				$tomail = $tostudent['mail'];
				echo '发送给'+$tomail;
				$mail->addTo($tomail);
				$title = $collegearray[$app['college']].$app['teacher'].'老师决定在'.gmdate('Y年m月d日H:i',$app['date']).'答疑['.$app['class'].']';
				$content = '亲爱的'.$tostudent['nickname'].'同学:'."\n    ".$title.'，请做好相关准备，祝你学业进步！';
				$content .= "\n-------------\n".'    四川大学网上第二课堂';
				$mail->setSubject("$title");
				$mail->setBodyText("$content");
				$mail->setFrom('cooljiansir@163.com');
				$mail->send();
			}
		} 
		catch (Zend_Exception $e) {
		// Here you can log an Zend_Mail exceptions
			echo $e->getMessage();
		}
	}

	private function sendcancelmailtostudent($id)
	{
	    $this->mailConfigure();
	    try {
	    	// defines gmail smtp infrastructure as default for any email message originated by Zend_Mail.

// 	    	$mail = new Zend_Mail();
// 	    	$mail->setBodyText('testing gmail');
// 	    	$mail->setFrom('cooljiansir@163.com');
// 	    	$mail->addTo('1534509022@qq.com');
// 	    	$mail->setSubject('静态测试TestSubject—–');
// 	    	$mail->send();
// 	    	echo '已发送';
	    
		    $dbstudentappo = new Application_Model_Studentappo();
		    $dbapp = new Application_Model_Appiontment();
		    $dbstudent = new Application_Model_Students();
		    $allstudent = $dbstudentappo->fetchAll("`toid`=$id");
		    $app = $dbapp->fetchRow("`id`=$id");
		    
		    $collegeconfig = new Zend_Config_Ini(APPLICATION_PATH .'/configs/college.ini','college');
		    $collegearray = $collegeconfig->toArray();
			//print_r($allstudent);
		    foreach($allstudent as $student)
		    {
		        $mail = new Zend_Mail();
		        $studentname = $student['studentname'];
		        $where = "`nickname` = \"$studentname\"";
		        $tostudent = $dbstudent->fetchRow($where);
		        if($tostudent!=null)$tostudent = $tostudent->toArray();
		    	$tomail = $tostudent['mail'];
		    	$mail->addTo($tomail);
		    	$title = $collegearray[$app['college']].$app['teacher'].'老师取消了在'.gmdate('Y年m月d日H:i',$app['date']).'答疑['.$app['class'].']';
// 		    	$title = $collegearray[$app['college']].$app['teacher'].'老师决定在'.gmdate('Y年m月d日H:i',$app['date']).'答疑['.$app['class'].']';
		    	$content = '亲爱的'.$tostudent['nickname'].'同学:'."\n    ".'非常遗憾，'.$title.'，请做好相关准备，祝你学业进步！';
		    	$content .= "\n-------------\n".'    四川大学网上第二课堂';
		    	$mail->setSubject("$title");
		    	$mail->setBodyText($content);
		    	$mail->setFrom('cooljiansir@163.com');
		    	$mail->send();    	
		    }
	    }
	    catch (Zend_Exception $e) {
	    	// Here you can log an Zend_Mail exceptions
	        echo $e->getMessage();
	    }
	}
}
